import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../utils/navigation_util.dart';
import '../datasources/splash_repository_impl.dart';
import '../entity/splash_bean.dart';
import '../intent/splash_state.dart';

class SplashViewModel extends StateNotifier<SplashState> {
  final SplashRepositoryImpl repositoryImpl;

  SplashViewModel(this.repositoryImpl) : super(SplashState());


  ///初始化数据的方法
  void initData() {
    state = state.copyWith(appState: '获取当前版本信息');
    _checkPlatform();
  }

  void _checkPlatform() {
    if (kIsWeb) {
      print('当前运行在 Web 浏览器中');
      state = state.copyWith(appState: '当前运行在 Web 浏览器中');
      navigationUtil.goMainPage();
    } else {
      print("当前运行在移动端或桌面端（非 Web）");
      if (Platform.isAndroid) {
        print('运行在 Android 端');
        state = state.copyWith(appState: '运行在 Android 端');
        _fetchData();
      } else if (Platform.isIOS) {
        print('运行在 iOS 端');
        state = state.copyWith(appState: '运行在 iOS 端');
        // _goMainPage();
      } else if (Platform.isWindows) {
        print('运行在 Windows 端');
        state = state.copyWith(appState: '运行在 Windows 端');
        // _goMainPage();
      } else if (Platform.isMacOS) {
        print('运行在 macOS 端');
        state = state.copyWith(appState: '运行在 macOS 端');
        // _goMainPage();
      } else if (Platform.isLinux) {
        print('运行在 Linux 端');
        state = state.copyWith(appState: '运行在 Linux 端');
        // _goMainPage();
      } else if (Platform.isFuchsia) {
        print('运行在 Fuchsia 端');
        state = state.copyWith(appState: '运行在 Fuchsia 端');
        // _goMainPage();
      }
    }
  }

  ///联网获取最新版本
  Future<void> _fetchData() async {
    /// 开屏页主要功能
    /// 1显示当前版本号
    /// 2查看是否有网,
    ///   没有提示需要联网才能使用
    ///   有,联网获取最新版本信息
    ///     如果当前版本跟最新版本不一样
    ///       下载最新版本
    ///         安装最新版本
    ///     如果一样,进入首页
    ///
    ///
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String buildNumber = packageInfo.buildNumber;
    int? currentVersionNumber = int.tryParse(buildNumber);
    state = state.copyWith(appState: buildNumber + '   ' + '${num}');

    final List<ConnectivityResult> connectivityResult = await (Connectivity().checkConnectivity());
    //此条件仅用于演示目的，以解释每种连接类型。
    //使用符合您要求的条件。
    if (connectivityResult.contains(ConnectivityResult.mobile)) {
      //移动网络可用。
      state = state.copyWith(appState: '移动网络可用');
      _toNext(currentVersionNumber);
    } else if (connectivityResult.contains(ConnectivityResult.wifi)) {
      //Wi-fi可用。
      //Android注意事项：
      //当手机和Wi-Fi都打开时，系统将仅将Wi-Fi作为活动网络类型返回
      state = state.copyWith(appState: 'Wi-fi可用');
      _toNext(currentVersionNumber);
    } else if (connectivityResult.contains(ConnectivityResult.ethernet)) {
      //以太网连接可用。
      state = state.copyWith(appState: '以太网连接可用');
    } else if (connectivityResult.contains(ConnectivityResult.vpn)) {
      //Vpn连接已激活。
      //iOS和macOS的注意事项：
      //[vpn]没有单独的网络接口类型。
      //它在任何设备（包括模拟器）上返回[其他]
      state = state.copyWith(appState: 'Vpn连接已激活');
    } else if (connectivityResult.contains(ConnectivityResult.bluetooth)) {
      //蓝牙连接可用。
      state = state.copyWith(appState: '蓝牙连接可用');
    } else if (connectivityResult.contains(ConnectivityResult.other)) {
      //连接到不在上述网络中的网络。
      state = state.copyWith(appState: '连接到不在上述网络中的网络');
    } else if (connectivityResult.contains(ConnectivityResult.none)) {
      //没有可用的网络类型
      state = state.copyWith(appState: '没有可用的网络,此软件需要联网才能使用');
    }
  }

  Future<void> _toNext(int? currentVersionNumber) async {
    final updateBean = await repositoryImpl.getDataForNet();
    final json = splashBeanToJson(updateBean);
    print(json);
    state = state.copyWith(appState: json);
    if (updateBean.version != currentVersionNumber) {
      state = state.copyWith(appState: '已是最新版本不需要更新');
      navigationUtil.goMainPage();
    } else {
      state = state.copyWith(appState: '不是最新版本需要更新');
      _downloadApk('http://117.72.114.24:8083/xiaohuanger/3.apk');
    }
  }

  Future<bool> _requestStoragePermission() async {
    if (Platform.isAndroid) {
      // Android 13+ 使用新的权限
      if (await Permission.storage.request().isGranted || await Permission.manageExternalStorage.request().isGranted) {
        return true;
      }

      // 对于较低版本的Android
      if (await Permission.storage.request().isGranted) {
        return true;
      }

      return false;
    }
    return true; // iOS不需要存储权限
  }

  Future<String> _getDownloadPath() async {
    Directory? directory;

    if (Platform.isAndroid) {
      // 获取外部存储的Downloads目录
      directory = Directory('/storage/emulated/0/Download');
      if (!directory.existsSync()) {
        // 如果Downloads目录不存在，使用应用的外部存储目录
        directory = await getExternalStorageDirectory();
      }
    } else {
      // iOS使用应用文档目录
      directory = await getApplicationDocumentsDirectory();
    }

    return directory?.path ?? '';
  }

  Future<void> _downloadApk(String url) async {
    // 请求存储权限
    if (!await _requestStoragePermission()) {
      state = state.copyWith(appState: '存储权限被拒绝');
      return;
    }
    try {
      state = state.copyWith(appState: '准备下载...', progress: 0.0);
      // 获取下载路径
      String downloadDir = await _getDownloadPath();
      String fileName = '3.apk';
      String savePath = '$downloadDir/$fileName';
      state = state.copyWith(appState: '开始下载...', downloadPath: savePath);
      await repositoryImpl.downloadApk(url, savePath, (received, total) {
        if (total != -1) {
          state = state.copyWith(appState: '下载中... ${(received / 1024 / 1024).toStringAsFixed(1)}MB / ${(total / 1024 / 1024).toStringAsFixed(1)}MB', progress: received / total);
        }
      });
      state = state.copyWith(appState: '下载完成！\n保存路径: $savePath');
      _installApk(savePath);
    } on DioException catch (e) {

      state = state.copyWith(appState:'下载失败: ${_getDioErrorMessage(e)}');
    } catch (e) {

      state = state.copyWith(appState:'下载失败: $e');
    }
  }
  String _getDioErrorMessage(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        return '连接超时';
      case DioExceptionType.sendTimeout:
        return '发送超时';
      case DioExceptionType.receiveTimeout:
        return '接收超时';
      case DioExceptionType.connectionError:
        return '连接错误';
      case DioExceptionType.badResponse:
        return '服务器响应错误: ${e.response?.statusCode}';
      case DioExceptionType.cancel:
        return '下载已取消';
      default:
        return e.message ?? '未知错误';
    }
  }
  Future<void> _installApk(String apkPath) async {
    // 请求权限
    if (!await Permission.requestInstallPackages.isGranted) {
      await Permission.requestInstallPackages.request();
    }
    final result = await OpenFile.open(apkPath);
    print('打开结果: ${result.message}');
  }

}
